

//HBuilder jsdoc地址：http://ask.dcloud.net.cn/article/129


///////////////////////////window.simple.start
(function(simple){
	
	// =======================================================
	// window-缓存.
	// =======================================================
	
	/**
	 * @description window对象.
	 */
	simple.window = {};
	
	
	/**
	 * @description 停止网页的加载.保存视频文件，音频文件.
	 * 
	 * 
	 * @example
	 * simple.window.stop();
	 * 
	 * 
	 */
	simple.window.stop = function(){
		if (!!(window.attachEvent && !window.opera)){
			document.execCommand("stop"); }
		else{
			window.stop();
		}
	};
	
	/**
	 * @description 获取音视频时间.
	 * 
	 * 
	 * @example
	 * 
	 var config = {
			url:"http://cdn.ixueyidian.com/api_files/video/music/file/20151215/1450151394568017045.mp4?v=121",
		    onWait:function(){
		    	//等待获取.
		    },
		    onComplete:function(metaData){
		    	//完成获取.
		    	//metaData.alert();弹出信息.
		    	//metaData.log();//log日志.
		    	//metaData.duration;//原始时间.带有小数点.
		    	//metaData.durationInt;//原始时间.不带有小数点.
		    	//metaData.durationFormat;//格式化: 3分20秒
		    }
	 };
	 simple.window.getVideoMeta(config);
	 * 
	 * 
	 */
	simple.window.getVideoMeta = function(config){
		var ele = document.createElement("video"); 
		ele.src=config.url;
		if(config.onWait){
			config.onWait();
		}
		var timer = setInterval(function() {
			if(ele.readyState>0){
				clearInterval(timer);
				if(config.onComplete){
					var metaData = {};
					var duration = ele.duration;
					metaData.duration = duration;
					metaData.durationInt = parseInt(duration);
					metaData.durationFormat = parseInt(duration/60)+"分"+parseInt(duration%60)+"秒";
					metaData.alert = function(){
						alert(JSON.stringify(this));
					};
					metaData.log = function(){
						console.log(JSON.stringify(this));
					};
					ele = null;
					config.onComplete(metaData);
				}
				simple.window.stop();
			}
		}, 100);
	};
	
	
	// =======================================================
	// storage-缓存.
	// =======================================================
	
	/**
	 * @description 本地缓存对象.
	 */
	simple.localStorage = {};//本地缓存对象.
	
	/**
	 * @description 获取本地缓存数据.
	 * 
	 * @param {String} key = [|]   缓存key.
	 * @param {String} dataType = [json|]可选值json | 
	 * 
	 * @example
	 * <p>获取缓存数据（String）:</p>
	 * simple.localStorage.get("test");
	 * 
	 * <p>获取缓存数据（json）:</p>
	 * simple.localStorage.get("test","json");
	 * 
	 */
	simple.localStorage.get = function(key,dataType){
		if(localStorage){
			var value = localStorage.getItem((key));
			if(value != null && dataType != undefined){
				if("json" == dataType){
					value = simple.json.toJson(value);
				}
			}
//			if(defaultValue != undefined && value == null){
//				value = defaultValue;
//			}
			return value;
		}
	};
	
	/**
	 * @description 设置本地缓存数据.
	 * 
	 * @param {String} key = [|]   缓存key.
	 * @param {String} value = [|]   缓存对象.
	 */
	simple.localStorage.set = function(key,value){
		if(localStorage){
			if(value instanceof Object){
				localStorage.setItem(key,simple.json.toStr(value));
			}else{
				localStorage.setItem(key,value);
			}
			
		}
	};
	
	/**
	 * @description  移除本地缓存数据.
	 * 
	 * @param {String} key = [|]   缓存key.
	 */
	simple.localStorage.remove = function(key){
		if(localStorage){
			localStorage.removeItem(key);
		}
	};
	
	/**
	 * @description  移除全部本地缓存数据.
	 * 
	 */
	simple.localStorage.clear = function(){
		if(localStorage){
			localStorage.clear();
		}
	};
	
	
	/**
	 * @description 会话缓存对象.
	 */
	simple.sessionStorage = {};
	
	/**
	 * @description 获取本地缓存数据.
	 * 
	 * @param {String} key = [|]   缓存key.
	 * 
 	 * @example
	 * <p>获取缓存数据（String）:</p>
	 * simple.sessionStorage.get("test");
	 * 
	 * <p>获取缓存数据（json）:</p>
	 * simple.sessionStorage.get("test","json");
	 * 
	 */
	simple.sessionStorage.get = function(key,dataType){
		if(sessionStorage){
			var value = sessionStorage.getItem((key));
			if(value != null && dataType != undefined){
				if("json" == dataType){
					value = simple.json.toJson(value);
				}
			}
			return value;
		}
	};
	
	/**
	 * @description 设置会话缓存数据
	 * 
	 * 
	 * @param {String} key = [|]   缓存key.
	 * @param {Object} value = [|] 缓存数据，可以是字符串，或者json对象.
	 * 
	 * @example
	 * simple.sessionStorage.set("test","hello");
	 * 
	 */
	simple.sessionStorage.set = function(key,value){
		if(sessionStorage){
			if(value instanceof Object){
				sessionStorage.setItem(key,simple.json.toStr(value));
			}else{
				sessionStorage.setItem(key,value);
			}
			
		}
	};
	
	/**
	 * @description 移除本地缓存数据.
	 * 
	 * @param {String} key = [|]   缓存key.
	 */
	simple.sessionStorage.remove = function(key){
		if(sessionStorage){
			sessionStorage.removeItem(key);
		}
	};
	
	/**
	 * @description 移除全部本地缓存数据.
	 * 
	 */
	simple.sessionStorage.clear = function(){
		if(sessionStorage){
			sessionStorage.clear();
		}
	};
	
	
	
	// =======================================================
	// json-json操作.
	// =======================================================
	/**
	 * @description  json-json操作.
	 */
	simple.json = {};//json对象.
	
	/**
	 * @description 转换成json字符串.
	 */
	simple.json.toStr = function(json){
		return JSON.stringify(json); 
	};
	
	/**
	 * @description 转换成json对象.
	 */
	simple.json.toJson = function(jsonStr){
		//JSON.parse(jsonstr); //可以将json字符串转换成json对象 
		//浏览器支持的转换方式(Firefox，chrome，opera，safari，ie9，ie8)等浏览器：
		return eval('(' + jsonStr + ')');
	};
	
	
	// =======================================================
	// 日志操作.
	// =======================================================
	/**
	 * @description  日志操作 ,log. (用于输出普通信息)
	 */
	simple.log = function(msg,level){
		var dataJson = {};
		dataJson.apiUrl = "baseTools/simpleLog";
		dataJson.level = level || "log";
		
		if(msg instanceof Object){
			dataJson.msg = simple.json.toStr(msg);
		}else{
			dataJson.msg = msg;
		}
		
		
		dataJson.action = "put";
		//dataJson.time = new Date().getTime();
		var config = {isShow:false};
		ajaxForUpdate(dataJson,function(data){
			console.dir(data);
		},config);
	};
	
	/**
	 * 错误信息. (用于输出错误信息)
	 */
	simple.error = function(msg){
		simple.log(msg,"error");
	};
	
	/**
	 *  提示信息. (用于输出提示性信息)
	 */
	simple.info = function(msg){
		simple.log(msg,"info");
	};
	
	/**
	 * 输出警示信息 (用于输出警示信息)
	 */
	simple.warn = function(msg){
		simple.log(msg,"warn");
	};
	
})(window.simple={});




// =======================================================
// 调用系统方法.
// =======================================================

//数组包含:
Array.prototype.contains = function(item){
	return RegExp("\\b"+item+"\\b").test(this);
};

//数组移除:index.
Array.prototype.removeAt = function(index){
	if(index<0){  //如果n<0，则不进行任何操作。
		return this;
	}else{
		return this.slice(0,index).concat(this.slice(index+1,this.length));
	}
};
//数组移除:obj.
Array.prototype.remove=function(obj){ 
	var index=this.indexOf(obj); 
	if (index>=0){ 
		return this.removeAt(index); 
	}
	return this;
}; 



//String
/**去掉两边的空格 */
String.prototype.trim = function(){// 去掉两边的空格...
	return this.replace(/(^\s*)|(\s*$)/g, "");
}; 
String.prototype.reverse = function(){//颠倒字符串.
	var arr = this.split("");	// 将字符串进行拆分，每一个字母为一个数组元素
	arr = arr.reverse();	// 将数组颠倒
	return arr.join("");	// 将数组合并成字符串,不用什么分隔符号
};

/**替换所有.*/
String.prototype.replaceAll = function(s1,s2){  
	return this.replace(new RegExp(s1,"gm"),s2);  
};



//Date
/**
	//对Date的扩展，将 Date 转化为指定格式的String
	//月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
	//年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
	//例子： 
	//(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
	//(new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
*/
Date.prototype.format = function (fmt) { //author: meizz 
	fmt = fmt || "yyyy-MM-dd hh:mm:ss";
	 var o = {
	     "M+": this.getMonth() + 1, //月份 
	     "d+": this.getDate(), //日 
	     "h+": this.getHours(), //小时 
	     "m+": this.getMinutes(), //分 
	     "s+": this.getSeconds(), //秒 
	     "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
	     "S": this.getMilliseconds() //毫秒 
	 };
	 if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	 for (var k in o)
	 if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	 return fmt;
};


///////////////////////////window.simple.end






// =======================================================
// 字符串处理.
// =======================================================



/**
 * 去除html标签.
 */
function removeHTMLTag(str) {
    str = str.replace(/<\/?[^>]*>/g,''); //去除HTML tag
    str = str.replace(/[ | ]*\n/g,'\n'); //去除行尾空白
    //str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
    str=str.replace(/&nbsp;/ig,'');//去掉&nbsp;
    return str;
}

/**
 * //删除左右两端的空格
 * @param {Object} str
 * @return {TypeName} 
 */
function trim(str){ //删除左右两端的空格
	return str.replace(/(^\s*)|(\s*$)/g, "");
}

/**
 * //删除左边的空格
 * @param {Object} str
 * @return {TypeName} 
 */
function ltrim(str){ //删除左边的空格
	return str.replace(/(^\s*)/g,"");
}

/**
 * //删除右边的空格
 * @param {Object} str
 * @return {TypeName} 
 */
function rtrim(str){ //删除右边的空格
	return str.replace(/(\s*$)/g,"");
}


function getPointString(str,length){
	if(str.length>length){
		return str.substr(0,length)+'...';
	}else{
		return str;
	}
}





// =================================================
// 表格操作
// =================================================

/**
 * 表格删除行.
 * @param {Object} obj:可以是包含在tr里的任何元素.
 */
function tableDeleteRow(obj){
		// 获取到rowIndex.
		var tmp = obj.tagName;
		while(tmp.toLowerCase() != 'tr'){
			obj = obj.parentNode;
			tmp = obj.tagName;
		}
		var row_tr = obj.rowIndex;//var row_tr = obj.parentNode.parentNode.rowIndex;//获取当前行数
		
		//获取table.
		obj = obj.parentNode;
		tmp = obj.tagName;
		while(tmp.toLowerCase() != 'table'){
			obj = obj.parentNode;
			tmp = obj.tagName;
		}
		//var table = document.getElementById("mytable");//获取表格对象
		//table.deleteRow(row_tr);
		obj.deleteRow(row_tr);
}


// ==========================================================
// tab 标签标签操作.
// ==========================================================

/**
 * 获取tag object.
 * @param {Object} id
 * @return {TypeName} 
 */
function get(id){
	return document.getElementById(id);	
}
/**
 * 获得焦点.
 */
function focus(id){
	get(id).focus();
}

/**
 * div 容器赋值.
 * @param {Object} id
 * @param {Object} html
 */
function html(id,html){
	get(id).innerHTML = html;
}

/**
 * inut value 设值.
 * @param {Object} id
 * @param {Object} txt
 */
function value(id,txt){
	get(id).value = txt;
}

/**
 * 点击事件.
 * @param {Object} id
 */
function click(id){
	get(id).click();
}

/**
 * show tag.
 * @param id
 */
function show(id){
	get(id).style.display = "";
}

/**
 * hide tag.
 * @param id
 */
function hide(id){
	get(id).style.display = "none";
}

/**
 * 是否都是数字.
 */
function isDigit(num){
	var reg=/^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 ，判断正整数用/^[1-9]+[0-9]*]*$/
	if(!reg.test(num)){
		return false;
	}else {
		return true;
	}
}

/**
 * 显示or隐藏.
 * @param {Object} divId
 */
function showOrHide(divId){
	var div = document.getElementById(divId);
	if(div.style.display == "none"){
		div.style.display = "";
	}else{
		div.style.display = "none";
	}
}


// ==========================================================
// Window操作.
// ==========================================================

/**
 * js 获取basePath.
 * 
 * 
 * 第二版本：修改by Angel in 2016-03-19,之前的算法有问题.
 * 参考:http://blog.csdn.net/lihaiyun718/article/details/7249487
 * 
 * 第三版本：针对于/的访问还是有问题,这个版本进行了优化,但是不是最好的.
 * 
 * @return {TypeName} 
 */
function getBasePath(){
//	var location = (window.location+'').split('/');
//	location =  location[0]+'//'+location[2]+'/'+location[3]+"/";
	var basePath = $("base").attr("href");
	if(basePath == undefined){
		//获取当前网址，如： http://localhost:8080/ems/Pages/Basic/Person.jsp
	    var curWwwPath = window.document.location.href;
	    //获取主机地址之后的目录，如： /ems/Pages/Basic/Person.jsp
	    var pathName = window.document.location.pathname;
	    var pos = curWwwPath.indexOf(pathName);
	    //获取主机地址，如： http://localhost:8080
	    var localhostPath = curWwwPath.substring(0, pos);
	    //获取带"/"的项目名，如：/ems
	    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
	    //获取项目的basePath   http://localhost:8080/ems/
	    var basePath=localhostPath+projectName+"/";
	}
	return basePath;
}

/**
 * 
 * return project name,for example：wx
 * @returns
 */
function getContextPath(){
	//return project name,for example：wx
	var localObj = window.location;
	var contextPath = localObj.pathname.split("/")[1];
	return contextPath;
}



/**
 * 刷新页面.
 */
function refresh(time){
	if(time){
		window.setTimeout(function(){
			window.location.href = window.location.href;
		},time*1000);
	}else{
		window.location.href = window.location.href;
	}
}

/**
 * 页面条件跳转.
 */
function gotoPage(path,timeout){
	if(timeout !=  undefined){
		setTimeout(function(){
			if(path.indexOf("http")>=0){
				window.location.href = path;
			}else{
				window.location.href = getBasePath()+path;
			}
		},timeout);
	}else{
		if(path.indexOf("http")>=0){
			window.location.href = path;
		}else{
			window.location.href = getBasePath()+path;
		}
	}
}


////////////////////////////////////////////////////////键盘监听的方法(start)////////////////////////////

/**
 * 获取event事件,支持IE和Firefox. 
 * 
 var evt = getEvent();
  if(evt != null && evt.keyCode == 13)
  {
	  doLogin();
  }
 */
function getEvent(){     
    if(document.all)    
    	return window.event;        
    func=getEvent.caller;            
    while(func!=null){    
      	var arg0=func.arguments[0];
        if(arg0){
           if((arg0.constructor==Event || arg0.constructor==MouseEvent)
             || (typeof(arg0)=="object" && arg0.preventDefault && arg0.stopPropagation)){    
                return arg0;
            }
        }
      	func=func.caller;
    }
    return null;
}

/**
 * <p>Function: 在body里监听键盘输入. </p
 * 
 * <p> demo:  <body onkeypress="onEnterKey(13,add());" > </p>
 * 
 * 
 * 
 * @param {Object} keyCode: 键盘值. Enter  = 13.
 * @param {Object} fun: 执行函数.
 */
function onEnterKey(keyCode,fun){
	var evt = getEvent();
	if(evt != null && evt.keyCode == keyCode){
		fun.call();
	}
}



/**
 * 事件.  
 * 
 * 需要在js中 有inputCtrlEnter ，inputEnter（需要监听哪个就重新哪个方法.）
 */
function doEnterKey()
{
  var evt = getEvent();
  if(evt != null){
	  if(evt.keyCode == 13){//Enter事件.
		  if(typeof inputEnter == "function"){
			 inputEnter();
		  }
	  }
	  
	  //alert((evt.ctrlKey && evt.keyCode ==10));
	  if(evt.ctrlKey && (evt.keyCode ==13 || evt.keyCode ==10)){//Ctrl+Enter,firefox= (evt.keyCode=13),google是等于10.
		  if(typeof inputCtrlEnter == "function"){
			inputCtrlEnter();
		  }
	  }
  }
}

/**
 * 页面条件跳转. 会延迟3s.
 */
function gotoPage3(path){
	window.setTimeout(function(){
		window.location.href = getBasePath()+path;
	},3000);
}

////////////////////////////////////////////////////////键盘监听的方法(end)////////////////////////////






////////////////////////////////////////////////////////锁定页面的方法(start)////////////////////////////
//加载时数据锁定页面方法① 启动保护罩Author:lxq
var parent_20130102;
var isCrossOrigin_20210512;
/**
 * 2017.11.2: 修复页面有滚动条加载条显示在上面的问题：loading中修改为position:fixed (position:absolute);
 */
function showLoading() {
	 var showStr = "<b>  数据加载中...</b>";
	
	 var img =  "<img  src='"+getBasePath()+"res/theme/loading.gif' style='display:inline;vertical-align:middle;' align='absmiddle'/>";
	 
	 var clientWidth = document.body.clientWidth;
	 if(clientWidth==0){
		 clientWidth = window.screen.width;
	 }
	 var clientHeight = document.body.scrollHeight;
//	 alert(window.innerHeight+"--"+ window.screen.height +"--"+clientHeight+"--"+document.body.clientHeight );

	 var left =clientWidth-160;
	 var top = 0;
	 left = left/2/clientWidth*100;
	 top = document.body.scrollTop;
	
	 var heightType = 0;
	 if(top == 0){
		 top = (window.innerHeight-60)/2;
		 heightType = 1;
		 
	 }
	 
	 if(top<0){
		 top = window.screen.height/2-100;
	 }else{
		 if(heightType==0){
			 top=top+window.screen.height/2-100;
		 }
	 }
	 
	 var leftAndTop ="top:"+top+"px; left:"+left+"%;";//pc:left:45%,top:45%; 
	 var loading = "<div style='moz-border-radius: 5px;-khtml-border-radius: 5px;-webkit-border-radius: 5px;border-radius: 5px;padding:5px;   alpha(Opacity=80);-moz-opacity:0.8;opacity: 0.8;border:solid"+
	 			"1px #000;z-index:99999;font-size:16px;color:#FFF;font-family:楷体; "+
				 "background:#001;position:fixed;"+leftAndTop+";;padding:15px;'>"+
		  		  img+showStr+"</div>";
		  		  
	var bg =  "<div id='filltop' "+
				"style='position:absolute;background-color:#F7F7F7;z-index:99999999;top:0px; left:0px; "+
				"width:100%; height:"+clientHeight+"px;filter:alpha(opacity=50);opacity: 0.5;-moz-opacity: 0.5'></div>"; 
	
	
	parent_20130102 = parent; 
	var count = 0;
	isCrossOrigin_20210512 = false;
	while(parent_20130102 != null){
		try{
			if(parent_20130102.document.body.tagName =="FRAMESET"){
				break;
			}else{
				parent_20130102 = parent_20130102.parent;
				count++;
				if(count == 3){
					break;
				}
			}
		}catch(e){
			isCrossOrigin_20210512 = true;
			//console.warn(e);
			break;
		}
	}
	 
	if(!isCrossOrigin_20210512 && parent_20130102.document.body.tagName =="FRAMESET"){//使用FRAMESET框架的时候.
		
		var length= parent_20130102.window.frames.length;
		
		leftAndTop = "top:30%; left:30%;";
		loading = "<div id='page_loading' style='moz-border-radius: 5px;-khtml-border-radius: 5px;-webkit-border-radius: 5px;border-radius: 5px;padding:5px;   alpha(Opacity=80);-moz-opacity:0.8;opacity: 0.8;  border:solid"+
	 			"1px #000;z-index:994;font-size:16px;color:#FFF;font-family:楷体;"+
				 "background:#001;position:absolute;"+leftAndTop+" ;padding:15px;'>&nbsp;"+
		  		  img+showStr+"</div>";
		
		for(var i=0;i<length;i++){
			var w = parent_20130102.window.frames[i];
			
			w.document.body.style.overflow = 'hidden';
			
			var div= parent_20130102.document.createElement("div");
			
		
			
			if(w == window){//当前页面. ---在tab中存在问题.(未进行解决.)
				div.innerHTML=loading;
			}else{
				if(w.name == ('mainFrame')){//解决tab文件.
					div.innerHTML=loading;
				}
			}
			
			
			
			div.innerHTML=div.innerHTML+bg;
			div.setAttribute("id", "page_loading");
			
			//alert(div.innerHTML);
			//w.document.body.innerHTML = w.document.body.innerHTML + div.innerHTML;
			w.document.body.appendChild(div);
			//w.document.body.insertBefore(div, w.document.body.childNodes[0]); 
		}
		
	}else{
		var accessWindow = parent;
		if(isCrossOrigin_20210512){
			accessWindow = window;
		}
		accessWindow.document.body.style.overflow = 'hidden';
		var div= accessWindow.document.createElement("div");
		div.innerHTML=loading+bg;
		div.setAttribute("id", "page_loading");
		accessWindow.document.body.appendChild(div);
	}
	
}
//加载数时据锁定页面方法② 隐藏保护罩 a：1 隐藏 Author:lxq
function hideLoading(){
	if(parent_20130102 !=null && !isCrossOrigin_20210512 && parent_20130102.document.body.tagName =="FRAMESET"){//使用FRAMESET框架的时候.
		var length=parent_20130102.window.frames.length;
		
		for(var i=0;i<length;i++){
			var w = parent_20130102.window.frames[i];
			if(w == null || w==undefined){
				continue;
			}
			w.document.body.style.overflow = '';
			var div =w.document.getElementById("page_loading"); 
			var top = w.document.getElementById("filltop");
			
			if(div !==null){
				div.parentNode.removeChild(div);   
				div=null;
			}    
			
			if(top!= null){
				top.parentNode.removeChild(top); 
				top = null;
			}
		}
	}else{
		var accessWindow = parent;
		if(isCrossOrigin_20210512){
			accessWindow = window;
		}
		accessWindow.document.body.style.overflow = ''; 
		var div =accessWindow.document.getElementById("page_loading"); 
		if(div !==null){
			div.parentNode.removeChild(div);   
			div=null;
		}    
	}
}
////////////////////////////////////////////////////////锁定页面的方法(end)////////////////////////////


// ==================================================
// check 方法.
// ==================================================

/**
 * 是否是图片类型.
 * @param {Object} fileName
 * @return {TypeName} 是图片返回true,否者返回false.
 */
function isImage(fileName){
	if(/\.(gif|jpg|jpeg|png|GIF|JPG|PNG|bmp|BMP)$/.test(fileName)){
		return true;
	}else{
		return false;
	}
}

/**
 * 判断是否是IE浏览器,是的话，返回true,否者返回false.
 * @return {TypeName} 
 */
function isIE(){
	var b = false;
	if(navigator.userAgent.indexOf("MSIE")>0) { 
        b = true;
  	}	
	return b;
}


/**
 * 判断是否是非负正数 >=0
 * @param val
 * @returns {Boolean}
 */
function isInt(value) {
 
    var pattern =  /^[1-9]\d*|0$/; //匹配非负整数 /^[0-9]+.?[0-9]*$/;  
    //value = value.replace(/[^\d]/g, "");
    if (!pattern.test(value)) {
        return false;
    }else{
    	return true;
    }
}

/**
 * 判断是不是合理的邮箱.
 * @returns {Boolean}
 */
function isEmail(email){
	var myreg = /^([a-zA-Z0-9]+[_|\-|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\-|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
	if(!myreg.test(email.trim())){
		return false;
	}
	return true;
}

/**
 * 是否是合理的手机号.
 * @param tel
 * @returns {Boolean}
 */
function isPhoneNumber( tel){
	 var reg = /^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/;
	 if (reg.test(tel)) {
	     return true;
	 }else{
	     return false;
	 };
}
//
///**
// * 是否是合理的手机号.
// * @param tel
// * @returns {Boolean}
// */
//function isPhoneNumber( tel){
//	var reg = /^0?1[3|4|5|7|8][0-9]\d{8}$/;
//	if (reg.test(tel)) {
//		return true;
//	}else{
//		return false;
//	};
//}

// =================================================
// 数学函数....
// =================================================

// =========================================
// 数学函数,随机函数.
// =========================================
 
/*
 * 
 * 	alert(Math.uuid());
 * Generate a random uuid.
 *
 * USAGE: Math.uuid(length, radix)
 *   length - the desired number of characters
 *   radix  - the number of allowable values for each character.
 *
 * EXAMPLES:
 *   // No arguments  - returns RFC4122, version 4 ID
 *   >>> Math.uuid()
 *   "92329D39-6F5C-4520-ABFC-AAB64544E172"
 *
 *   // One argument - returns ID of the specified length
 *   >>> Math.uuid(15)     // 15 character ID (default base=62)
 *   "VcydxgltxrVZSTV"
 *
 *   // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62)
 *   >>> Math.uuid(8, 2)  // 8 character ID (base=2)
 *   "01001010"
 *   >>> Math.uuid(8, 10) // 8 character ID (base=10)
 *   "47473046"
 *   >>> Math.uuid(8, 16) // 8 character ID (base=16)
 *   "098F4D35"
 */
(function() {
  // Private array of chars to use
  var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
 
  Math.uuid = function (len, radix) {
    var chars = CHARS, uuid = [], i;
    radix = radix || chars.length;
 
    if (len) {
      // Compact form
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
      // rfc4122, version 4 form
      var r;
 
      // rfc4122 requires these characters
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
 
      // Fill in random data.  At i==19 set the high bits of clock sequence as
      // per rfc4122, sec. 4.1.5
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random()*16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
 
    return uuid.join('');
  };
 
  // A more performant, but slightly bulkier, RFC4122v4 solution.  We boost performance
  // by minimizing calls to random()
  Math.uuidFast = function() {
    var chars = CHARS, uuid = new Array(36), rnd=0, r;
    for (var i = 0; i < 36; i++) {
      if (i==8 || i==13 ||  i==18 || i==23) {
        uuid[i] = '-';
      } else if (i==14) {
        uuid[i] = '4';
      } else {
        if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
        r = rnd & 0xf;
        rnd = rnd >> 4;
        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
      }
    }
    return uuid.join('');
  };
 
  // A more compact, but less performant, RFC4122v4 solution:
  Math.uuidCompact = function() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
      return v.toString(16);
    });
  };
})();


function getRandomLetter(len){
	var word = '';
	for(var i=0;i<len;i++){
		eval( " word +=" +  '"\\u' + (Math.round(Math.random() * 20901) + 19968).toString(16)+'"');
	}
	return word;
}


/*
 * 随机获取一句话.
 */
function getRandomWord(){
	var word = new Array();
	word.push("无法评论？");
	word.push("小伙伴们快来看啊");
	word.push("大意了，大意了");
	word.push("带着满身的伤痕 ");
	word.push("转发微博");
	word.push("这好像是大陆的结婚证。");
	word.push("你 ，，你， 你，，你");
	word.push("我，我，我，很正常...");
	word.push("什么会不会....你们这脑袋真是开了....");
	word.push("你们脖子都歪了，先扭正了在好好看...");
	word.push("我觉得不错，我已经看过了。当然个人喜好不一样，不能保证你也喜欢。但是我觉得你喜欢 看成龙大哥的电影，你就觉得不错！");
	word.push("哦，我喜欢成龙，刚好我现在在电影院兼职哈哈哈，可以免费看");
	word.push("你们是一伙的，赞 的不算数....");
	word.push("学校新建的庙吧....我也没有见过....");
	word.push("她就在那里，不移不动。你随时可以回去看");
	word.push("这是在校内吗？有谁去参加，知道的");
	word.push("我也常想起他");
	word.push("恩恩，我记得那时候他和关系很好的哦!!!!");
	word.push("然后你们还经常一起讨论数学难题.....");
	word.push("Good");
	word.push("很好");
	word.push("赞一个");
	word.push("关注我");
	word.push("我喜欢");
	word.push("不错");
	word.push("这动态不好");
	word.push("少扯淡不行么？");
	word.push("放假倒计时~");
	word.push("致敬曾经的五年,五年前你在做什么，五年后呢？");
	word.push("2014第一天，感谢朋友放弃休息来家聚会，房子热了，感情深了，CC嗨了，吃饭都是888…");
	word.push("半夜里，朦胧中听到由远及近的高跟鞋声确实挺恐怖的，昨晚我听到了@新雨");
	word.push("做事不靠谱，不如回家种红薯，鄙视一下自己……");
	word.push("时光像坐火车，过去的景色虽然美好，可你总要向前走。用最多的梦想面对未来吧。2014，注定会遇见最好的自己。我们一起努力！");
	word.push("回过头 连个说话的人都没有TAT");
	word.push("很想省略掉从起床到出门的这段时间(起床困难户)");
	var index = parseInt(Math.random()*word.length);
	return word[index];
}


	// =======================================================
	// Array.数组处理.
	// =======================================================
	/**删除数组中的元素
	 * 
	 	var typeIds = new Array();
		typeIds.push(1);
		typeIds.push(2);
		typeIds.push(3);
		typeIds = typeIds.deleteByIndex(0)
		typeIds.push(5);
		alert(typeIds);
	 */
	Array.prototype.deleteByIndex=function(n) {//n表示第几项，从0开始算起。
		//prototype为对象原型，注意这里为对象增加自定义方法的方法。
		if(n<0)//如果n<0，则不进行任何操作。
			return this;
		else
			return this.slice(0,n).concat(this.slice(n+1,this.length));
	};
	
	/**删除数组中的元素
	 *  var typeIds = new Array();
		typeIds.push(1);
		typeIds.push(2);
		typeIds.push(3);
		typeIds = typeIds.deleteByValue(2);
		typeIds.push(5);
		alert(typeIds);
	 */
	Array.prototype.deleteByValue=function(value) {//n表示第几项，从0开始算起。
		var array = this;
		for(var i=0;i<this.length;i++){
			//alert(array[i]+"--"+value);
			if(array[i] == value){
				return  this.deleteByIndex(i);
			}
		}
	};


	
/**
 * 获取浏览器的基本信息.
document.writeln("语言版本: "+browser.language);
document.writeln(" 是否为移动终端: "+browser.versions.mobile);
document.writeln(" ios终端: "+browser.versions.ios);
document.writeln(" android终端: "+browser.versions.android);
document.writeln(" 是否为iPhone: "+browser.versions.iPhone);
document.writeln(" 是否iPad: "+browser.versions.iPad);
document.writeln(navigator.userAgent); 
*/
function getBrowse(){
	  var browser={
	    	versions:function(){
	            var u = navigator.userAgent, app = navigator.appVersion;
	            return {         //移动终端浏览器版本信息
	                trident: u.indexOf('Trident') > -1, //IE内核
	                presto: u.indexOf('Presto') > -1, //opera内核
	                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
	                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
	                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
	                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
	                android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
	                iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器
	                iPad: u.indexOf('iPad') > -1, //是否iPad
	                webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
	            };
	         }(),
	         language:(navigator.browserLanguage || navigator.language).toLowerCase()
	};
	
	return browser;
}	
	
/**
 * 货币转换.  分 转换为 元.
 * @param varl
 * @returns
 */
function f2y(val,separator){
	if(separator == undefined){
		separator = ",";
	}
	var str = (val/100).toFixed(2) + '';
	var intSum = str.substring(0,str.indexOf(".")).replace( /\B(?=(?:\d{3})+$)/g, separator );//取到整数部分
	var dot = str.substring(str.length,str.indexOf("."));//取到小数部分
	var ret = intSum + dot;
	return ret;
}	



/**
 * 日期计算，加减日期（天.）
 * @param day
 * @returns {Date}
 */
function date_day(day){
	var today=new Date();
	var t=today.getTime()+1000*60*60*24*(day);
	var dd = new Date(t);
	return dd;
}



/**
 *  字符串时间转换为日期对象.
 * @param dateStr 
 * @param separator
 * @returns {Date}
 */
function dateStrToDate(dateStr){
	dateStr = dateStr.replaceAll("-","/");
	return new Date(dateStr);
}


/**
 * 提醒.调用方式：window.hint("您图片有点大，小微正在努力的处理...");
 */
(function(){
	window.hint = function(hint){
		 var leftAndTop = "top:0;left:0;";
		 var showStr = hint;
		 var loading = "<div id='hint_20150115' style='"+leftAndTop+";width:100%;alpha(Opacity=80);-moz-opacity:0.8;opacity: 0.8;border:solid"+
			"1px #000;z-index:994;font-size:16px;color:#FFF;font-family:楷体;"+
			 "background:#001;position:fixed;z-index:10;'><div style=';padding:15px;'>"+showStr+"</div></div>";
		var div= window.document.createElement("div");
		div.innerHTML = loading;
		window.document.body.appendChild(div);
		window.setTimeout(function(){
			//remove.
			removeHint();
		},5000);
	};
	
	function removeHint(){
		var div =window.document.getElementById("hint_20150115"); 
		if(div !==null){
			div.parentNode.removeChild(div);
			div=null;
		}  
	}
	
})();

function img_head_err(obj){
	obj.src = getBasePath()+"res/img/default_head.jpg";
}

/**
 * js 获取问号后面的params.
 * @param key
 * @returns
 */
function queryString(key,defaultValue){
    var paras = location.search;
    var value = null;
    if(paras){
        var arr = paras.substr(1).split("&");
        var data;
        var size = arr.length;
        for(var i=0;i<size;i++){
            data = arr[i].split("=");
            if(data[0] == key){
            		value =  data[1];
            		break;
            }
        }
    }
    if(defaultValue && (value ==null || value==undefined || value == '')){
    		value = defaultValue;
    }
    return value;
}

/**
 * 先从参数后面获取，找不到从SessionStorage中获取，否则为defaultValue
 */
function queryStringOrSessionStorage(key,defaultValue){
	var value = queryString(key);
	if(defaultValue && (value ==null || value==undefined || value == '')){
		value = simple.sessionStorage.get(key);
		if(defaultValue && (value ==null || value==undefined || value == '')){
	    		value = defaultValue;
	    }
	}
	return value;
}

/**
 * 打印日志.
 */
function log(msg){
	console.log(msg);
}

function tag_img(basePath,head,imgW,imgH,defaultValue){
	var html =  "";
	if(head == "" || head==undefined){
		html += defaultValue;
	}else{
		if(head.indexOf("http")>=0){
		}else{
			head = basePath+head;
		}
		html += '	      <img class="preview" src="'+head+'"  width="'+imgW+'" height="'+imgH+'"/>'; 
	}
	return html;
}

function getHttpPath(basePath,head,defaultHead){
	var html =  "";
	if(head != null && head != undefined){
		if(head.indexOf("http")>=0||head.indexOf("cdn.c8hr.com")>=0){
			html =head ;
		}else{
			html = basePath+head;
		}
	}
	if(html == '' && defaultHead != undefined){
		html = defaultHead;
	}
	return html;
}

/**
 * 延迟动作.
 * @param time
 * @param fn
 */
function timeout(time,fn){
	window.setTimeout(function(){
		fn.call();
	},time*1000);
}

/***
 * 返回到上一个页面.
 */
function back(index){
	if(isInt(index)){
		window.history.go(-index);

	}else{
		window.history.back();
	}
	
	
}

/**
 * 转换成json 字符串.
 * @param json
 * @returns
 */
function toJsonString(json){
	return JSON.stringify(json); 
}

/**
 * 转换成json对象.
 * @param jsonStr
 * @returns
 */
function toJson(jsonStr){
	return eval('(' + jsonStr + ')');
}

/**复选框初始化.*/
function initCheckbox(id,defalutValue){
	if(defalutValue == 1){
		$("#"+id).attr("checked","checked");
	}else{
		$("#"+id).removeAttr("checked");
	}
}

/**单选框初始化.*/
function initRadio(name,value){
	$("input[name="+name+"][value="+value+"]").attr("checked",true);
}

/**
 * 随机获取颜色值.
 * @returns {String}
 */
function getRandomColor(){ 
	return "#"+("00000"+((Math.random()*16777215+0.5)>>0).toString(16)).slice(-6); 
}

/**
 * 初始化表单.
 * @param data
 */
function initForm(data){
	var d = data;
	for(var key in d){ 
		var input = $("#"+key);
		var obj = input[0];
		try {
			if(input.length>0){
				if(obj.tagName  == "TEXTAREA"){
					input.val(d[key]);
				}else if(obj.tagName == "INPUT"){
					if(obj.type =="text"  || obj.type =="number"){
						input.val(d[key]);
					}else if(obj.type == "radio"){
						
					}else if(obj.type == "checkbox"){
						if(d[key] == 1){
							input.attr("checked","checked");
						}else{
							input.removeAttr("checked");
						}
					}
				}else if(obj.tagName == 'SELECT'){
					input.val(d[key]);
				}
			}else{
				if($("input[name="+key+"][type='radio']")){
					$("input[name="+key+"][value="+d[key]+"]").attr("checked",true);
				}
			}
		} catch (e) {
			
		}
	} 
}



/**
 * 计算年龄，周岁. birthday2age(ages("1980-03-22"));   
 * @param str
 * @returns
 */
function birthday2age(strBirthday){       
	var returnAge;
	var strBirthdayArr=strBirthday.split("-");
	var birthYear = strBirthdayArr[0];
	var birthMonth = strBirthdayArr[1];
	var birthDay = strBirthdayArr[2];
	
	d = new Date();
	var nowYear = d.getFullYear();
	var nowMonth = d.getMonth() + 1;
	var nowDay = d.getDate();
	if(nowYear == birthYear){
		returnAge = 0;//同年 则为0岁
	}else{
		var ageDiff = nowYear - birthYear ; //年之差
		if(ageDiff > 0){
			if(nowMonth == birthMonth){
				var dayDiff = nowDay - birthDay;//日之差
				if(dayDiff < 0)
				{returnAge = ageDiff - 1;}
				else
				{returnAge = ageDiff ;}
			}else{
				var monthDiff = nowMonth - birthMonth;//月之差
				if(monthDiff < 0)
				{returnAge = ageDiff - 1;}
				else
				{returnAge = ageDiff ;}
			}
		}else{
			returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天}
		}
		return returnAge;//返回周岁年龄
	}
}

/**
 * 强制刷新.
 */
function forceRefresh(){
	self.location=document.referrer;
}


/**
 * //json transfer to array.
	var arrays = jsonToArray(rs.datas,["registerTime","nums"]);//alert(arrays.registerTime); alert(arrays.nums);
 * @param datas
 * @param keys
 * @returns {___anonymous24667_24668}
 */
function jsonToArray(datas,keys){
	var rs = {};
	var sizeKeys = keys.length;
	for(var i=0;i<sizeKeys;i++){
		rs[keys[i]] = new Array();
	}
	var size = datas.length;
	var d = null;
	for(var i=0;i<size;i++){
		d = datas[i];
		for(var j=0;j<sizeKeys;j++){
			rs[keys[j]].push(d[keys[j]]);
		}
	}
	return rs;
}

function ifNullOrEmpty(str,nullOrEmptyValue,elseValue){
	if(str == null || str == undefined || str == ""){
		str = nullOrEmptyValue;
	}else{
		if(elseValue){
			str = elseValue;
		}
	}
	return str;
}

function getDaysBySecond(millisecond){
    var second = (millisecond/1000);
	var days = parseInt(second/(24*3600));
	var hour = parseInt(second%(24*3600)/3600);
	var minute = Math.floor(second%(24*3600)%3600/60,0);
	var sec = Math.floor(second%(24*3600)%3600%60);
	var rs = "";
	if(days >0){
		rs += days+"天";
	}
	if(hour >0){
		rs += hour+"小时";
	}
	if(minute >0){
		rs += minute+"分";
	}
	if(sec >0){
		rs += sec+"秒";
	}else {
		//=0.
		if(rs == ""){
			rs += sec+"秒";
		}
	}
	return rs;
}

/**
 * 播放音频文件.
 */
function playAudio(audioSrc){
	var audioId = "simple_playAudio_"+audioSrc.replaceAll("/","_").replaceAll(".","");
	var audioObj = $("#"+audioId);
	if($("#simple_playAudio").length==0){
		var audio = "<audio id='"+audioId+"' src='"+audioSrc+"' autoplay='autoplay'></audio>";
		$("body").append(audio);
	}else{
		audioObj.get(0).play();
	}
}

/**
 * 文本动画;
 * @param e
 * @param text
 */
function animateForText(e,text){
	var $i=$("<b>").text(text);
	var x=e.pageX,y=e.pageY;
	$i.css({top:y-20,left:x,position:"absolute",color:"#E94F06"});
	$("body").append($i);
	$i.animate({top:y-180,opacity:0.2,"font-size":"60px"},2000,function(){
		$i.remove();
	});
	e.stopPropagation();
}


/**
 * 是否是合理的URL.
 * @param str_url
 * @returns {Boolean}
 */
function isURL(str_url){
    var strRegex = "^((https|http|ftp|rtsp|mms)?://)"
    + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
    + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
    + "|" // 允许IP和DOMAIN（域名）
    + "([0-9a-z_!~*'()-]+\.)*" // 域名- www.
    + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
    + "[a-z]{2,6})" // first level domain- .com or .museum
    + "(:[0-9]{1,4})?" // 端口- :80
    + "((/?)|" // a slash isn't required if there is no file name
    + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
    var re=new RegExp(strRegex);
    //re.test()
    if (re.test(str_url)){
        return (true);
    }else{
        return (false);
    }
}

function isTelephone(value){
	//判断座机格式的  
	value = value.replace("-","");
	//var partten = /^(\d{3,4}\-)?\d{7,8}$/i;   //座机格式是 010-98909899  
	var partten = /^0(([1-9]\d)|([3-9]\d{2}))\d{4,8}$/; //没有中间那段 -的 座机格式是 01098909899  
	var zuoji=partten.test(value);  
	if(zuoji){  
		return true;
	}else{  
		return false;  
	}
}

function isMP4(fileName){
	if(/\.(MP4|mp4)$/.test(fileName)){
		return true;
	}else{
		return false;
	}
}


function showMsg(message,textStatus,conf){
	var successOrError="#FFF";
	var level="alert-success";
	conf = conf || {};
	var time=3000;
	var autoRemove = true;
	if(textStatus!=null){
		if(textStatus == 'error'){
			successOrError= "#ED9C28";
		}
	}
	
	if(conf.time !=null){
		time=conf.time;
	}
	if(conf.refresh){
		autoRemove = false;
		message += "，点击<a href='javascript:refresh();' style='color:#FFF;'>重新加载</a>";
	}
	
	var width = $(window).width()/2;
	width = width-(message.length)*10/2;
	var tmp = "";
	
	var MsgDiv="<div id='div_showmsg' class='  alert "+level+" fade in  offset4 ' style='padding:16px;position: fixed;border-radius:5px;background:#001;z-index:999999;overflow: hidden;  line-height: 1.5;  left: 50%; top: 50%;transform: translate(-50%, -50%); text-align: center;filter:alpha(Opacity=80);-moz-opacity:0.8;opacity: 0.8;"+tmp+"'>"+
				"<span style='color:"+successOrError+";font-weight:bold;'>"+message+"</span>"+
				"</div>";
	if(document.getElementById('div_showmsg') != null){
		//已经存在了.
		$("#div_showmsg").remove();
	}
	$("body").append(MsgDiv);
	
	if(autoRemove){
		$("#div_showmsg").delay(time).animate({'top':'hide'},function(){
			 //$(this).hide();
			 $(this).remove();
		});
	}
	
	
}



//替换邮箱字符
function regEmailInAsterisk(email) {
	if (String(email).indexOf('@') > 0) {
		var str = email.split('@'),
		_s = '';
		if (str[0].length > 3) {
			for (var i = 0; i < str[0].length - 3; i++) {
				_s += '*';
			}
		}
		var new_email = str[0].substr(0, 3) + _s + '@' + str[1];
	}
	return new_email;
}

//替换手机字符
function regMobileInAsterisk(mobile) {
	if (mobile.length > 7) {
		var new_mobile = mobile.substr(0, 3) + '****' + mobile.substr(7);
	}
	return new_mobile;
}

//匹配字符串...
function regStrInAsterisk (str,frontLen,endLen) { 
	var length = str.length;
	if(length  == 2){//姓名只有2位的情况.
		endLen = 0;
	}
	var len = length-frontLen-endLen;
	
	var xing = '';
	for (var i=0;i<len;i++) {
	xing+='*';
	}
	return str.substring(0,frontLen)+xing+str.substring(str.length-endLen);
}

/**
 * js 调用app代码
 * for example: 
 * 
 * jsInvokeApp("api","testApp",{"uid":"1007","token":"token=12345678"});
 * 
 * 
 * 如果没有参数可以这么调用：
 * 
 * jsInvokeApp("api","testApp");
 * 
 * @param scheme
 * @param method
 * @param dataJson
 */
function jsInvokeApp(scheme,method,dataJson){
	try {
		var browse = getBrowse();
		if(browse.versions.mobile){
			if(window != null && window.api != null){//Android.
//				window.api.doClick(id,"这是字符串.");
				if(dataJson == undefined){
					//alert("scheme="+scheme+"--method="+method);
					var methods = "window."+scheme+"."+method+"()";
					 //alert(methods+"--"+window.eval);
					 window.eval(methods);
					 //window.api.getUidAndToken();
					//window.api.getUidAndToken();
				}else{
					var str = JSON.stringify(dataJson);
					eval("window."+scheme+"."+method+"('"+str+"')");
				}
			}else{//iOS
//				var uri = 'api://webview.doClick#{"uid":'+id+',"token":"mytoken"}';
				//$("#msg").append(dataJson);
				if(dataJson == undefined){
					var uri = scheme+"://webview."+method+"#";
					//$("#msg").append("12uri="+uri);
					window.location = uri;
				}else{
					var str = JSON.stringify(dataJson);
					var uri = scheme+"://webview."+method+"#"+str;
					window.location = uri;
				}
			}
		}
	} catch (e) {
		alert(e.message);
	}
}

/**
 * 直接访问api的ajax.
 * @param dataJson
 */
function ajaxForApi(dataJson,fn){
	var op = {};
	op.url = getBasePath()+"apiSimulate.json";
	op.dataJson = dataJson;
	op.dataJson.apiUrl_2015_03_14 = dataJson.apiUrl;
	try {
		dataJson.uid = _uid;
		dataJson.token = _token;
	} catch (e) {
	}
	op.dataJson.ajaxForApi_2015_05_28 = "ajaxForApi_2015_05_28";
	ajax(op,fn);
}

/**
 * 访问admin的ajax,是否需要登录，具体看接口情况.
 * @param dataJson
 * @param fn
 */
function ajaxForAdmin(dataJson,fn){
	var op = {};
	op.url = getBasePath()+"common.json";
	op.dataJson = dataJson;
	ajax(op,fn);
}

/**
 * 自动访问API还是admin.
 * 是否需要登录，具体看接口情况.
 * @param dataJson
 * @param fn
 */
function ajaxForAuto(dataJson,fn){
	if(isMiniProgram()){
		//小程序.
		ajaxForApi(dataJson,fn);
	}else{
		ajaxForAdmin(dataJson,fn);
	}
}

/**
 * 禁止复制粘贴的行为
 */
function denyCtrlCV(){
	// deny right mouse/right click
	document.oncontextmenu = function(){ return false; };
	// deny select
	document.onselectstart = function(){ return false; };
	// deny copy
	document.oncopy = function(){ return false; };
	// deny cut
	document.oncut = function(){ return false; };
	// deny paste
	document.onpaste = function(){ return false; };
}

/**
 * 是否是小程序.
 */
function isMiniProgram(){
	return window.__wxjs_environment === 'miniprogram'  || (navigator.userAgent.match(/micromessenger/i) && navigator.userAgent.match(/miniprogram/i))  ;
}
/**
 * 清除cookie
 */
//清空cookie
function clearCookie() {
    var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
        for (var i = keys.length; i--;) {
            document.cookie = keys[i] + '=0;path=/;expires=' + new Date(0).toUTCString();//清除当前域名下的,例如：m.kevis.com
            document.cookie = keys[i] + '=0;path=/;domain=' + document.domain + ';expires=' + new Date(0).toUTCString();//清除当前域名下的，例如 .m.kevis.com
            document.cookie = keys[i] + '=0;path=/;domain=kevis.com;expires=' + new Date(0).toUTCString();//清除一级域名下的或指定的，例如 .kevis.com
        }
    }
}